# coding=utf-8
from django.db.models import Q

from sutras import enums, models
from sutras.utils import tools


def get_info(user_transcription_id):
    """
    获取邀请信息
    """
    user_transcription = models.UserTranscription.objects.filter(
        id=user_transcription_id).first()
    if not user_transcription:
        return None

    sutra_edition = user_transcription.sutra_edition
    info = {
        "sutra": {
            "cover_url": sutra_edition.cover_url,
            "name": sutra_edition.name,
            "id": sutra_edition.id,
        },
        "transcription": {
            "id": user_transcription.id,
            "vow_time": user_transcription.vow_time,
            "vow_text": user_transcription.vow_text,
        }
    }

    return info


def entry_assistance(user, user_transcription_id):
    """
    进入抄写
    """
    user_transcription = models.UserTranscription.objects.filter(
        id=user_transcription_id).first()
    page_num = calculate_available_page(user_transcription)

    if page_num == -1:
        return -1

    # 创建同修关系
    models.AssistantRelation.objects.get_or_create(
        sutra_edition=user_transcription.sutra_edition,
        user_transcription=user_transcription,
        owner_user=user_transcription.user,
        assistant_user=user,
        page_num=page_num)
    sutra_edition_page = models.SutraEditionPage.objects.filter(
        sutra_edition=user_transcription.sutra_edition,
        page_num=page_num).first()
    # 创建抄写页记录
    models.UserPageTranscription.objects.get_or_create(
        user_transcription=user_transcription,
        page_num=page_num,
        assistant_user=user,
        total_char_num=sutra_edition_page.total_char_num,
    )
    return page_num


def calculate_available_page(user_transcription):
    """
    计算可助抄页码

    Returns
    -------
    int
        页码，如未找到可助抄页则返回-1
    """
    # 总页码
    total_page_num = user_transcription.sutra_edition.total_page_num
    total_page_nums = set(range(total_page_num))
    # 自抄页数
    self_page_nums = models.UserPageTranscription.objects.filter(
        user_transcription=user_transcription,
        assistant_user__isnull=True).values_list("page_num", flat=True)
    self_page_nums = set(self_page_nums)
    # 助抄页数(未完成+已完成)
    condition = Q(
        user_transcription=user_transcription, assistant_user__isnull=False)
    condition &= Q(status=enums.UserPageTranscription.finished) | Q(
        status=enums.UserPageTranscription.not_finished)
    assistance_page_nums = set(models.UserPageTranscription(
        condition).values_list("page_num", flat=True))

    # 可助抄页码
    available_page_nums = sorted(list(
        total_page_nums - self_page_nums - assistance_page_nums))
    if not available_page_nums:
        return -1
    return available_page_nums[0]


def get_assistants(user_transcription):
    """
    获取助抄人列表
    """
    assistant_ids = models.AssistantRelation.objects.filter(
        user_transcription=user_transcription).values_list(
            "assistant_user_id", flat=True)
    assistants = models.CustomUser.objects.filter(id__in=assistant_ids)
    return assistants


def get_assistant_info_datas(user_transcription):
    assistant_objs = get_assistants(user_transcription)
    open_ids = [assistant_obj.open_id
                for assistant_obj in assistant_objs]
    wx_infos = tools.get_wx_user_infos(open_ids)
    user_info_datas = {}

    for assistant_obj in assistant_objs:
        open_id = assistant_obj.open_id
        wx_info = wx_infos.get(open_id)
        user_info_datas[assistant_obj.uid] = {
            "uid": assistant_obj.uid,
            "nickname": wx_info["nickname"],
            "avatar_url": wx_info["headimgurl"],
            "page_count": 0,
            "finish_page_nums": [],
            "unfinish_page_nums": [],
            "abandonded_page_nums": [],
        }
    return user_info_datas


def get_assistance_details(user_transcription_id):
    """
    获取助抄详情
    """
    user_transcription = models.UserTranscription.objects.filter(
        id=user_transcription_id).first()
    if not user_transcription:
        return None

    assistant_info_datas = get_assistant_info_datas(user_transcription)
    assistant_page_objs = models.UserPageTranscription.objects.filter(
        user_transcription_id=user_transcription_id,
        assistant_user__isnull=False).order_by("page_num")
    for page_obj in assistant_page_objs:
        user_info = assistant_info_datas[page_obj.assistant_user.uid]
        user_info["page_count"] += 1
        if page_obj.status == enums.UserPageTranscription.finished:
            user_info["finish_page_nums"].append(page_obj.page_num)
        elif page_obj.status == enums.UserPageTranscription.not_finished:
            user_info["unfinish_page_nums"].append(page_obj.page_num)
        elif page_obj.status == enums.UserPageTranscription.abandoned:
            user_info["abandonded_page_nums"].append(page_obj.page_num)
    # 字典转list
    user_infos = [assistant_info_datas[uid]
                  for uid in sorted(assistant_info_datas)]

    details = {}
    details["sutra_name"] = user_transcription.sutra_edition.name
    details["assistant_user_count"] = len(assistant_page_objs)
    details["assistant_page_count"] = len(assistant_page_objs)
    details["users"] = user_infos

    return details
